<template>
  <div>
    姓名: <input v-model.trim="form.name" type="text" /><br />
    年龄: <input v-model.number="form.age" type="text" /><br />
    性别:
    <select v-model="form.gender">
      <option value="男">男</option>
      <option value="女">女</option></select
    ><br />
    <button @click="add">添加</button>
    <button @click="amend">修改</button>
    <br />
    <table border>
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="cancel(item.id)">删除</button>&nbsp;
            <button @click="compile(item.id)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        name: "",
        gender: "",
        age: "",
      },

      arr: [
        { id: 11, name: "Tom", gender: "男", age: 19 },
        { id: 22, name: "Jone", gender: "女", age: 21 },
      ],
    };
  },
  methods: {
    //非空判断
    add() {
      const { name, gender, age } = this.form;
      if (name === "" || gender === "" || age === "")
        return alert("请输入完整");
// 添加
      this.arr.push({
        name,
        gender,
        age,
      }),
      //清空
        this.form = {
          name: "",
          gender: "",
          age: "",
        };
    },
    // 删除
    cancel(id) {
      const index = this.arr.find((item) => item.id === id);
      this.arr.splice(index, 1);
    },
    // 数据回显
    compile(id){
      const obj=this.arr.find((item) => item.id === id);
      
      this.form={...obj}
    },
    // 数据修改
    amend(){
      const id=this.form.id
        const obj=this.arr.find((item) => item.id === id);
        obj.name=this.form.name,
        obj.gender=this.form.gender,
        obj.age=this.form.age,
        this.form = {
          name: "",
          gender: "",
          age: "",
        };

    }

  },
};
</script>

<style scoped>
table {
  /* border: 1px solid black; */
  border-collapse: collapse;
}
td,
th {
  padding: 10px;
}
</style>
